package com.telrob.tool;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OKHttpUtils {
    private static OkHttpClient client = null;
    private static final String TAG="zhang2";

    public static final String apiKey="rHIl=6DPVBVYCGqJ9eiTRGSkgek=";
    private static final String registerCode="GHcQNLMGMQxz7Zwc";

    private static final String baseUrl="http://api.heclouds.com/";
    static{
        client=new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .writeTimeout(1, TimeUnit.SECONDS)
                .readTimeout(1, TimeUnit.SECONDS)
                .build();
    }

    public static String get(String url){
        try{
            String urlTemp=baseUrl+url;
            Request request =new  Request.Builder()
                    .url(urlTemp)
                    .addHeader("api-key",apiKey)
                    .build();

            Call call=client.newCall(request);
            Response response=call.execute();
            String data=response.body().string();
            Log.i(TAG, data);
            return data;
        }catch(Exception e){
            Log.i(TAG, "http 发送失败");
            e.printStackTrace();
        }
        return null;
    }

    public static String post(String url,String json){
        try{
            String urlTemp=baseUrl+url;
            MediaType JSON = MediaType.parse("application/json;charset=utf-8");
            RequestBody body = RequestBody.create(JSON, json);
            Request request = new Request.Builder()
                    .url(urlTemp)
                    .addHeader("api-key",apiKey)
                    .post(body)
                    .build();
            Call call=client.newCall(request);
            Response response=call.execute();
            String data=response.body().string();
            Log.i(TAG, data);
            return data;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
